package cn.tedu.spring.security.dao.impl;

import cn.tedu.spring.security.dao.UserDao;
import cn.tedu.spring.security.pojo.User;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

@Service
public class UserDaoJdbcImpl implements UserDao {

    @Autowired JdbcTemplate jdbcTemplate;

    private RowMapper<User> rowMapper=(rs, rowNum) -> {
        User user = new User();
        user.setId(rs.getInt("id"))
            .setUsername(rs.getString("username"))
            .setPassword(rs.getString("password"))
            .setRoles(rs.getString("roles"));
        return user;
    };

    @Override public User getUserByUsername(String username) {
        String sql="SELECT id,username,password,roles FROM user WHERE username=?";
        User user= null;
        try {
            user = jdbcTemplate.queryForObject(sql,rowMapper,username);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override public List<User> findAll() {
        String sql="SELECT id,username,password,roles FROM user";
        List<User> users = jdbcTemplate.query(sql, rowMapper);
        return users;
    }
}
